package com.seocoo.worker.order;

import android.annotation.SuppressLint;
import android.arch.lifecycle.Lifecycle;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.contrarywind.view.WheelView;
import com.seocoo.worker.R;
import com.seocoo.worker.base.RxOrderRefrect;
import com.seocoo.worker.base.http.BasePageRsp;
import com.seocoo.worker.base.refresh.SwipeRefreshMoreLayout;
import com.seocoo.worker.friend.entity.RxEvaluateSuccess;
import com.seocoo.worker.order.adapter.OrderGoldAdapter;
import com.seocoo.worker.order.entity.RspGoldInstall;
import com.seocoo.worker.order.entity.RxCancelInstallSuccess;
import com.seocoo.worker.order.model.OrderGoldModel;
import com.seocoo.worker.order.model.OrderModel;
import com.seocoo.worker.order.req.ReqGoldInstall;
import com.sfh.lib.event.BusEvent;
import com.sfh.lib.mvvm.LiveDataMatch;
import com.sfh.lib.ui.MVVMFragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * author : Ssp
 * date   : 2020/2/23 16:25
 * desc   : 安装订单列表
 */
public class OrderGoldFragment extends MVVMFragment implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener, SwipeRefreshMoreLayout.OnLoadingListener {

    private SwipeRefreshMoreLayout swipe_refresh_more_layout;
    private String orderType;

    public static OrderGoldFragment newInstance(String orderType) {
        OrderGoldFragment fragment = new OrderGoldFragment();
        Bundle bundle = new Bundle();
        bundle.putString("orderType", orderType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public int getLayout() {
        return R.layout.order_install_fragment;
    }

    @Override
    public void initData(View view) {
        assert getArguments() != null;
        orderType = getArguments().getString("orderType");
        swipe_refresh_more_layout = view.findViewById(R.id.swipe_refresh_more_layout);
        OrderGoldAdapter adapter = new OrderGoldAdapter();
        swipe_refresh_more_layout.setAdapter(adapter, true);
        swipe_refresh_more_layout.setOnItemChildClickListener(this);
        swipe_refresh_more_layout.setOnItemClickListener(this);
        swipe_refresh_more_layout.setOnLoadingListener(this);
        swipe_refresh_more_layout.addItemDecorationSize(17);
        reFreshData();
    }

    public void reFreshData() {
        swipe_refresh_more_layout.onAutoRefresh();
    }

    @LiveDataMatch
    public void onQuerySuccess(BasePageRsp<RspGoldInstall> data) {
        swipe_refresh_more_layout.onRefreshCompale(data);
    }

    @LiveDataMatch
    public void onQueryError() {
        swipe_refresh_more_layout.onLoadMoreFail();
    }

    @Override
    public void onLoadMoreUI(int nowPage) {
        getViewModel(OrderGoldModel.class).refreshData(new ReqGoldInstall(nowPage, orderType));
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        int viewId = view.getId();
        List data = adapter.getData();
        if (data.isEmpty()) {
            return;
        }
        RspGoldInstall item = (RspGoldInstall) data.get(position);
        switch (viewId) {
            case R.id.tv_cancel:
                //取消测量
                getViewModel(OrderModel.class).cancelMeasure(item.getMeasureId());
                break;
            case R.id.tv_receiving:
                //接单
                getViewModel(OrderModel.class).takeOrder(item.getOrderId());
                break;
            case R.id.tv_relevance_friends:
                //设置测量时间
                initTimeSelect("设置测量时间", (date, v) -> {
                    String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                    @SuppressLint("SimpleDateFormat") String format = new SimpleDateFormat(strDateFormat).format(date);
                    getViewModel(OrderModel.class).setMeasureTime(item.getOrderId(), format, item.getMeasureId());
                });
                break;
            case R.id.tv_appointment_install_time:
                //录入测量信息
                OrderGoldMeasureActivity.start(getContext(), item.getOrderId());
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List data = adapter.getData();
        if (data.isEmpty()) {
            return;
        }
        RspGoldInstall item = (RspGoldInstall) data.get(position);
        OrderGoldDetailActivity.start(getActivity(), item.getOrderId());
    }

    @LiveDataMatch
    public void onTakeOrder(String orderId) {
        swipe_refresh_more_layout.onAutoRefresh();
    }

    @LiveDataMatch
    public void onCancelMeasure(String measureId) {
        swipe_refresh_more_layout.onAutoRefresh();
    }

    @LiveDataMatch
    public void onAddOrderMeasure() {
        swipe_refresh_more_layout.onAutoRefresh();
    }

    /**
     * 选择时间
     */
    @SuppressLint("SimpleDateFormat")
    private void initTimeSelect(String title, OnTimeSelectListener timeSelectListener) {
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat year = new SimpleDateFormat("yyyy");
        SimpleDateFormat moth = new SimpleDateFormat("MM");
        SimpleDateFormat day = new SimpleDateFormat("dd");
        Date date = new Date(timeMillis);
        Calendar startDate = Calendar.getInstance();
        startDate.set(Integer.parseInt(year.format(date)), Integer.parseInt(moth.format(date)) - 1, Integer.parseInt(day.format(date)));
        Calendar endDate = Calendar.getInstance();
        endDate.set(2080, 12, 30);
        Calendar selectedDate = Calendar.getInstance();
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(getContext(), timeSelectListener)
                .setTitleText(title)
                //时间选择器 ，自定义布局
                .setDividerColor(Color.parseColor("#999999"))
                .setDividerType(WheelView.DividerType.FILL)
                .setContentTextSize(20)
                .setDate(selectedDate)
                .isDialog(true)
                .setRangDate(startDate, endDate)
                //设置选中项的颜色
                .setTextColorCenter(Color.parseColor("#333333"))
                .setLabel("年", "月", "日", "时", "分", "")
                .isCenterLabel(false)
                //设置两横线之间的间隔倍数  m
                .setLineSpacingMultiplier(2.0f)
                .setTextXOffset(0, 0, 0, 0, 0, 0)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, true, true, false});
        timePickerBuilder.build().show();
    }

    @BusEvent(from = "推送消息刷新列表")
    public void refresh(RxOrderRefrect refrect) {
        if (this.isVisible() && Lifecycle.State.STARTED == this.getLifecycle().getCurrentState()) {
            reFreshData();
        }
    }

    @BusEvent(from = "刷新列表")
    public void refresh1(RxEvaluateSuccess result) {
        if (result.isSuccess()) {
            reFreshData();
        }
    }

    @BusEvent(from = "刷新列表")
    public void refresh2(RxCancelInstallSuccess result) {
        if (result.isCancelSuccess()) {
            reFreshData();
        }
    }
}
